package edu.hawaii.senin.iclouds.basics;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Helper calls to convert IDL reactions into regular XML
 * 
 * @author Administrator
 * 
 */
public class ReactionFactory {

  public ReactionFactory() {
    // does nothing
  }

  public ArrayList<Reaction> buildTheList(BufferedReader in) {
    ArrayList<Reaction> res = new ArrayList<Reaction>();
    String cLine = null;
    try {
      while ((cLine = in.readLine()) != null) {
        if (cLine.charAt(0) == ';') {
          continue;
        }
        else {
          if (cLine.substring(0, 10).equalsIgnoreCase("start_spec")) {
            // parse reaction
            int idx = cLine.indexOf("'", 0);
            int idx1 = cLine.indexOf("'", idx+1);
            String reactant1 = cLine.substring(idx+1, idx1);
            idx = cLine.indexOf("'", idx1+1);
            idx1 = cLine.indexOf("'", idx+1);
            String reactant2 = cLine.substring(idx+1, idx1);

            cLine = in.readLine();
            idx = cLine.indexOf("'", 0);
            idx1 = cLine.indexOf("'", idx+1);
            String product = cLine.substring(idx+1, idx1);

            cLine = in.readLine();
            idx = cLine.indexOf("[", 0);
            idx1 = cLine.indexOf("d", idx+1);
            String ebarrier = cLine.substring(idx+1, idx1);

            cLine = in.readLine();
            idx = cLine.indexOf("'", 0);
            idx1 = cLine.indexOf("'", idx+1);
            String type = cLine.substring(idx+1, idx1);

            // public Reaction(String description, Double eBarrier, Double rate, String type,
            // ArrayList<String> reactants, ArrayList<String> products) {
            ArrayList<String> reactants = new ArrayList<String>();
            reactants.add(reactant1);
            reactants.add(reactant2);
            ArrayList<String> products = new ArrayList<String>();
            products.add(product);
            Reaction r = new Reaction((reactant1 + reactant2 + "_" + product), Double
                .valueOf(ebarrier), 1.0, type, reactants, products);
            res.add(r);

          }
        }

      }
    }
    catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return res;
  }

  public void dumpToFile(ArrayList<Reaction> r, BufferedWriter out) throws IOException {
    for (Reaction rc : r) {
      rc.dumpToWriter(out);
    }
  }
}
